<template>
  <div>
    <common-login :checks="true" @toLogin="login" @getCode="getCode" ref="login"/>
    <!--<common-login :checks="true" @toLogin="$router.push('/teacherImpInfo')" @getCode="getCode" ref="login"/>-->
  </div>
</template>

<script>
import commonLogin from '@/components/commonLogin'
import api from '@/api'
import {wxAuth} from '@/utils/auth'
export default {
  name: 'login',
  data () {
    return {}
  },
  methods: {
    login (data) {
      let params = {
        ver_number: data.code,
        ver_phone: data.phone
      }
      api.teacherLogin({
        params,
        callback: res => {
          if (res.data.error_code === 0) {
            this.$toast.success({
              message: res.data.message,
              duration: 1000,
              forbidClick: true,
              onClose: () => {
                if (res.data.data.perfect === 2) {
                  this.$router.push('/teacherImpInfo')
                } else {
                  this.$router.push('/my/index')
                }
              }
            })
            localStorage.setItem('teacher_token', res.data.data.token)
            window.sessionStorage.setItem('user', JSON.stringify(res.data.data))
            this.$store.commit('SET_TEACHER', res.data.data)
            this.$store.commit('SET_TOKEN', res.data.data.token)
          } else {
            this.$toast(res.data.message)
            this.$refs['login'].setLoading()
          }
        }
      })
    },

    // 获取短信验证码
    getCode (phone) {
      api.teacherSendMsg({
        params: {phone, type: '1'},
        callback: res => {
          this.$toast(res.data.message)
          this.$refs['login'].setCodeStatus(res.data.error_code === 0)
        }
      })
    },

    getUserInfo (token) {
      let params = {
        token
      }
      api.teacherPersonal({
        params,
        callback: res => {
          if (res.data.error_code === 0) {
            window.sessionStorage.setItem('user', JSON.stringify(res.data.data))
            this.$store.commit('SET_TEACHER', res.data.data)
            if (res.data.data.perfect === 2) {
              this.$router.push('/teacherImpInfo')
            } else {
              this.$router.push('/my/index')
            }
          } else {
            localStorage.removeItem('teacher_token')
          }
        }
      })
    }
  },
  components: {
    commonLogin
  },
  created () {
    let user = localStorage.getItem('userInfo')
    let code = this.$route.query.code
    let token = localStorage.getItem('teacher_token')
    if (token) {
      this.getUserInfo(token)
    } else {
      if (code) {
        wxAuth(code)
      } else if (!user) {
        let href = encodeURIComponent(window.location.href)
        // http://sae.wecozhiku.com/admin/login/GetAuthorCode
        location.href = `http://sae.wecozhiku.com/admin/Wxapiaction/GetAuthorCode?url=${href}`
      }
    }
  }
}
</script>

<style scoped>
  .container{
    padding: 0 15px;
  }
</style>
